<script setup lang="ts">
import { onBeforeMount, reactive, ref } from 'vue'
import type { CreateProject } from '@/types/ProjectType'
import {
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type UploadInstance,
  type UploadRequestOptions
} from 'element-plus'
import { api, api_url } from '@/api/api'
import type { Category, CreateStandard, Types } from '@/types/StandardType'
import { useUserStore } from '@/stores/user'
import router from '@/router'

const categoryList = ref<Category[]>([])
const user = useUserStore()

onBeforeMount(() => {
  api.getAllCategory().then((resp) => {
    categoryList.value = resp
  })
})

const formData = reactive<CreateProject>({
  name: '',
  reason: '',
  creater_id: user.userInfo.id ?? -1,
  standard: []
})

const formRef = ref<FormInstance>()

const rules = reactive<FormRules<CreateProject>>({
  name: [{ required: true, message: '请填写项目名称', trigger: 'blur' }],
  reason: [{ required: true, message: '请填写申报理由', trigger: 'blur' }]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      console.log(formData)
      api.addProject(formData).then((resp) => {
        ElMessageBox.alert('创建成功!', '结果', {
          confirmButtonText: '分解参数'
        }).then(() => {
          //前往分解参数页面
          router.push('/home/createParameter/' + resp.id.toString())
        })
      })
    }
  })
}

function addStandard() {
  let x: CreateStandard = {
    category: '',
    type: '',
    name: '',
    file_uuid: '',
    iid: ''
  }
  formData.standard.push(x)
}

function uploadFile(params: UploadRequestOptions, x: number) {
  let data = new FormData()
  data.append('file', params.file)
  api.upload(data).then((resp) => {
    formData.standard[x].file_uuid = resp
  })
}

const toFile = (x: string) => {
  window.open(api_url + 'files/' + x)
}
const upload = ref<UploadInstance>()

const deleteStandard = (x: number) => {
  formData.standard.splice(x, 1)
}

function onCategoryChange(category: string) {
  if (
    !categoryList.value.some((x) => {
      return x.categoryName == category
    })
  ) {
    let new_category: Category = {
      categoryName: category,
      types: []
    }
    categoryList.value.push(new_category)
  }
}

function onTypeChange(category: string, type: string) {
  if (
    categoryList.value.some((x) => {
      return x.categoryName == category
    })
  ) {
    let _category: Category | undefined = categoryList.value.find((x) => {
      return x.categoryName == category
    })
    if (
      !_category?.types.some((x) => {
        return x.typeName == type
      })
    ) {
      let new_type: Types = {
        typeName: type
      }
      _category?.types.push(new_type)
    }
  }
}

function goBack() {
  router.push('/home/processingP')
}
</script>

<template>
  <div class="main">
    <h1 class="h1">创建项目</h1>
    <div class="create_form_box">
      <div class="sub">
        <el-page-header @back="goBack()"> </el-page-header>
      </div>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
        <div class="input_">
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="申报理由" prop="reason">
            <el-input
              v-model="formData.reason"
              type="textarea"
              :autosize="{ minRows: 2 }"
              placeholder="请输入理由"
              style="width: 50vw"
            ></el-input>
          </el-form-item>
        </div>
        <el-divider content-position="left" class="divider_">标准</el-divider>
        <el-table :data="formData.standard">
          <el-table-column type="index"></el-table-column>
          <el-table-column label="大类" width="fit-content">
            <template #default="scope">
              <el-select
                filterable
                allow-create
                v-model="scope.row.category"
                placeholder="Select"
                @change="onCategoryChange(scope.row.category)"
              >
                <el-option
                  v-for="item in categoryList"
                  :key="item?.id"
                  :label="item.categoryName"
                  :value="item.categoryName"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="类别" width="fit-content">
            <template #default="scope">
              <el-select
                v-model="scope.row.type"
                placeholder="Select"
                filterable
                allow-create
                @change="onTypeChange(scope.row.category, scope.row.type)"
              >
                <el-option
                  v-for="item in categoryList.find((x) => {
                    return x.categoryName == scope.row.category
                  })?.types"
                  :key="item?.id"
                  :label="item.typeName"
                  :value="item.typeName"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="标准名称" width="fit-content">
            <template #default="scope">
              <el-input
                v-model="scope.row.name"
                placeholder="标准名称"
                style="width: 10vw"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="编号（含年号）" width="fit-content">
            <template #default="scope">
              <el-input
                v-model="scope.row.iid"
                placeholder="编号（含年号）"
                style="width: 10vw"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="标准文件">
            <template #default="scope">
              <el-upload
                :limit="1"
                ref="upload"
                :show-file-list="false"
                :http-request="
                  (params: UploadRequestOptions) => {
                    return uploadFile(params, scope.$index)
                  }
                "
              >
                <template v-if="scope.row.file_uuid == ''" #trigger>
                  <el-button type="primary">选择文件</el-button>
                </template>
                <template v-else #tip>
                  <el-link @click="toFile(scope.row.file_uuid)">{{ scope.row.file_uuid }}</el-link>
                </template>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column label="" width="min-content">
            <template #default="scope"
              ><el-button
                type="danger"
                style="margin-left: 10px"
                @click="deleteStandard(scope.$index)"
                ><el-icon>
                  <Delete /> </el-icon></el-button></template
          ></el-table-column>
        </el-table>
        <div class="button_">
          <el-button type="primary" @click="addStandard()">添加标准</el-button>
          <el-button type="primary" @click="submitForm(formRef)">&emsp;提交&emsp;</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.main {
  width: 100%;

  .h1 {
    margin-left: 50px;
    margin-top: 50px;
  }
}

.create_form_box {
  margin-top: 40px;
  margin-left: 52px;
  margin-right: 40px;
  margin-bottom: 150px;
  padding: 38px 40px 80px 60px;
  border: solid 1px var(--el-border-color);
  box-shadow: var(--el-box-shadow-lighter);
}

.button_ {
  margin-top: 20px;
}

.divider_ {
  margin-top: 70px;
}

.input_ {
  margin-top: 10px;
  margin-left: -40px;
}

.el-input {
  width: 20vw;
}
</style>
